/**
 * There are code generation
 */
package com.neusoft.lohas.modules.ivm.service.product;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.neusoft.lohas.common.persistence.Page;
import com.neusoft.lohas.common.service.BaseService;
import com.neusoft.lohas.common.utils.StringUtils;
import com.neusoft.lohas.common.utils.Utils;
import com.neusoft.lohas.modules.ivm.dao.product.ProductDao;
import com.neusoft.lohas.modules.ivm.entity.product.Product;
import com.neusoft.lohas.modules.ivm.entity.product.ProductClassify;
import com.neusoft.lohas.modules.ivm.utils.MerchantUtils;
import com.neusoft.lohas.modules.ivm.utils.ProductUtils;

/**
 * 商品信息Service
 * @author Jackie.Liu
 * @version 2014-11-13
 */
@Component
@Transactional(readOnly = true)
public class ProductService extends BaseService {

	@Autowired
	private ProductDao productDao;
	
	public Product get(String id) {
		return productDao.get(id);
	}
	
	//loadMore:是否加载全部
	public Page<Product> find(Page<Product> page, Product product, String searchParam, String sort, boolean loadMore) {
		String sql = "select distinct pro.* from ivm_product pro "
					+" left join ivm_relationship_product_classify rel on pro.id = rel.product_id "
					+" left join ivm_product_classify cla on cla.id=rel.classify_id and cla.del_flag='0' "
					+" where pro.del_flag='0' "
					+" and pro.merchant_id='"+MerchantUtils.getMerchant().getId()+"'";
		if (StringUtils.isNotEmpty(searchParam)){
			sql += " and (pro.name like '%"+searchParam+"%'";
			if(isNumeric(searchParam)){
				sql += " or pro.code = "+searchParam+")";
			}else {
				sql += ")";
			}
		}
		/* if (product.getCode()!=null) {
			sql += " and pro.code = "+product.getCode();
		}
		if (StringUtils.isNotEmpty(product.getName())){
			sql += " and pro.name like '%"+product.getName()+"%'";
		}*/
		if (StringUtils.isNotEmpty(product.getOpenState())) {
			sql += " and pro.open_state = '"+product.getOpenState()+"'";
		}
		//库存查询（stock=1:有库存，stock=2:无库存，stock=3:全部）
		if(product.getStock() == 1){
			sql += " and pro.stock > 0";
		}else if(product.getStock() == 2){
			sql += " and pro.stock = 0";
		}
		//是否支持到付
		if(product.getToPay() != null && !product.getToPay().equals("")){
			sql += " and pro.to_pay = '"+product.getToPay()+"'";
		}
		//是否限购
		if(product.getIsPurchase() != null && !product.getIsPurchase().equals("")){
			if(product.getIsPurchase().equals("1")){//限购
				sql += " and pro.purchase_num > 0";
			}else if(product.getIsPurchase().equals("0")){
				sql += " and pro.purchase_num = 0";
			}
		}
		//库存方式：真实，虚拟
		if(product.getStockState() != null && !product.getStockState().equals("")){
			sql += " and pro.stock_state = '"+product.getStockState()+"'";
		}
		if (product.getClassify()!=null && StringUtils.isNotBlank(product.getClassify().getId())) {
			sql += " and cla.parent_id in ('"+product.getClassify().getId()+"')";
		}
		if (product.getClassifyIdList().size()>0) {
			String classifyIds = Utils.ListToString(product.getClassifyIdList(), null);
			if(classifyIds!=null)
				sql += " and cla.id in ("+classifyIds+")";
		}
		if(!"".equals(sort) && sort.split("#").length>0){
			page.setOrderBy(" "+sort.split("#")[0]+" "+sort.split("#")[1]);
		}
		if(loadMore) page.setPageSize(9999);
		return productDao.findBySql(page, sql, Product.class);
	}
	
	@Transactional(readOnly = false)
	public void save(Product product) {
		productDao.clear();
		productDao.save(product);
	}
	
	@Transactional(readOnly = false)
	public void save(List<Product> list) {
		productDao.clear();
		productDao.save(list);
	}
	
	@Transactional(readOnly = false)
	public void delete(String id) {
		productDao.deleteById(id);
	}
	
	public Product getProductByName(String merchantId, String name) {
		return productDao.findByName(merchantId, name);
	}
	
	public List<ProductClassify> findAllClassify(){
		return ProductUtils.getClassifyList();
	}
	
	public long getMaxCode(String merchantId){
		return productDao.getMaxCode(merchantId);
	}
	
	/**
	 * 根据商品编号获取商品信息
	 * @param merchantId
	 * @param code
	 * @return
	 */
	public Product getProductByCode(String merchantId, String code){
		DetachedCriteria dc = productDao.createDetachedCriteria();
		if (isNumeric(code)) {
			dc.add(Restrictions.or(
				Restrictions.and(
						Restrictions.eq("code", Long.valueOf(code))
				),
				Restrictions.and(
						Restrictions.eq("name", code)
				)
			));
		}else {
			dc.add(Restrictions.eq("name", code));
		}
		dc.add(Restrictions.eq(Product.FIELD_DEL_FLAG, Product.DEL_FLAG_NORMAL));
		if(StringUtils.isNotBlank(merchantId)){
			dc.add(Restrictions.eq("merchant.id", merchantId));
		}
		List<Product> list = productDao.find(dc);
		return list.size()>0?list.get(0):null;
	}
	
	/**
	 * 判断字符串是否为数字
	 */
	public boolean isNumeric(String str){ 
	   Pattern pattern = Pattern.compile("[0-9]*"); 
	   Matcher isNum = pattern.matcher(str);
	   if( !isNum.matches() ){
	       return false; 
	   } 
	   return true; 
	}

	/**
	 * 更新浏览次数
	 * @param id
	 */
	@Transactional(readOnly = false)
	public void updateScanNum(String id) {
		productDao.updateScanNum(id);
	}

	public List<Product> findSelects(String[] productIds) {
		DetachedCriteria dc = productDao.createDetachedCriteria();
		dc.add(Restrictions.in("id", productIds));
		dc.addOrder(org.hibernate.criterion.Order.desc("sort"));
		return productDao.find(dc);
	}
}
